<template>
  <div class="accont_Page">
    <!-- 卡片栏 -->
    <el-card v-if="show" class="box-card">
      <template #header>
        <div>
          <span>绑定账户</span>
        </div>
      </template>
      <div class="text_item">
        <!--银行卡图片 -->
        <div class="leftImg">
          <img :src="defaultBank" alt="" />
        </div>
        <!-- 银行图片 -->
        <div class="bankName">
          <div class="bankNumber">
            <div class="bankNumber_1" v-html="err"></div>
            <div v-if="Number(privacyTime) === 0" class="bankNumber_2">
              {{ hidden(bankArr.cardNumber, 3, 4) }}
            </div>
            <div v-else class="bankNumber_2">{{ bankArr.cardNumber }}</div>
          </div>
          <div class="bankNumber">
            <div class="bankNumber_1">持卡人：</div>
            <div class="bankNumber_1">{{ bankArr.cardName }}</div>
          </div>
        </div>
        <!-- 按钮 -->
        <div class="btnList">
          <div class="cutBank" @click="delBank(2)">解绑</div>
          <div class="changeBank" @click="replaceCard(3)">更换</div>
        </div>
      </div>
    </el-card>
    <el-card v-else>
      <template #header>
        <div>
          <span>绑定账户</span>
        </div>
      </template>
      <div class="text_item">
        <!--银行卡图片 -->
        <div class="leftImg">
          <img :src="defaultBank" alt="" />
        </div>
        <!-- 银行图片 -->
        <div class="noAccount">尚未绑定账户</div>
        <!-- 按钮 -->
        <div class="btnList">
          <div class="changeBank" @click="bindCard(1)">立即绑定</div>
        </div>
      </div>
    </el-card>

    <!-- 弹框开始 -->
    <el-dialog
      v-model="dialogData.isVisible"
      :title="dialogData.title"
      width="500px"
      :close-on-click-modal="false"
      center
      @close="closeDialog"
    >
      <!-- 绑定银行卡 -->
      <el-form
        v-if="dialogData.type === 1"
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
      >
        <el-form-item label="持卡人姓名" prop="cardName">
          <el-input v-model="form.cardName" maxlength="20" placeholder="请输入持卡人姓名" @onblur="btKeyUp" />
        </el-form-item>
        <el-form-item label="卡号" prop="cardNumber">
          <el-input
            v-model="form.cardNumber"
            placeholder="请输入卡号"
            maxlength="19"
            oninput="value=value.replace(/[^\d]/g,'')"
          />
        </el-form-item>
        <el-form-item label="银行" prop="bank">
          <el-select
            v-model="form.bank"
            filterable
            placeholder="请选择所属银行"
          >
            <el-option
              v-for="item in options"
              :key="item.dictName"
              :label="item.dictName"
              :value="item.dictId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="注册手机号" prop="phone">
          <el-input
            v-model="form.phone"
            placeholder="请输入手机号"
            oninput="value=value.replace(/[^\d]/g,'')"
            maxlength="11"
            style="width: 300px"
          >
            <template #append>
              <el-button
                type="primary"
                :loading="codeloading"
                @click="sendCode(form.phone)"
              >
                <span v-if="!codeloading">获取验证码</span>
                <span v-else>{{ count }} s</span>
              </el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="验证码" prop="code">
          <el-input
            v-model="form.code"
            placeholder="请输入验证码"
            style="width: 120px"
            oninput="value=value.replace(/[^\d]/g,'')"
            maxlength="6"
          />
        </el-form-item>
      </el-form>
      <!-- 解绑 -->
      <el-form
        v-if="dialogData.type === 2"
        ref="formRef"
        :model="unbinds"
        :rules="rules"
        label-width="120px"
      >
        <el-form-item label="注册手机号" prop="phone">
          <el-input
            v-model="unbinds.phone"
            placeholder="请输入手机号"
            maxlength="11"
            style="width: 300px"
          >
            <template #append>
              <el-button
                type="primary"
                :loading="codeloading"
                @click="sendCode(unbinds.phone)"
              >
                <span v-if="!codeloading">获取验证码</span>
                <span v-else>{{ count }} s</span>
              </el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="验证码" prop="code">
          <el-input v-model="unbinds.code" placeholder="请输入验证码" style="width: 120px" />
        </el-form-item>
      </el-form>
      <!-- 更换银行卡 -->
      <el-form
        v-if="dialogData.type === 3"
        ref="formRef"
        :model="card"
        :rules="rules"
        label-width="120px"
      >
        <!-- <p class="card">原绑定信息</p>
          <el-form-item label="原持卡人姓名" prop="cardName">
            <el-input v-model="card.cardName" />
          </el-form-item>
          <el-form-item label="原银行卡号" prop="oldCardNumber">
            <el-input v-model="card.oldCardNumber" />
          </el-form-item>
          <p class="card">新绑定信息</p>-->
        <el-form-item label="持卡人姓名" prop="cardName">
          <el-input v-model="card.cardName" placeholder="请输入持卡人姓名" maxlength="20" @onblur="btKeyUp" />
        </el-form-item>
        <el-form-item label="卡号" prop="cardNumber">
          <el-input
            v-if="cardNumberShow"
            :model-value="hidden(card.cardNumber, 3, 4)"
            oninput="value=value.replace(/[^\d]/g,'')"
            maxlength="19"
            @focus="focusCardNunberInput"
          />
          <el-input
            v-else
            v-model="card.cardNumber"
            placeholder="请输入卡号"
            maxlength="19"
            oninput="value=value.replace(/[^\d]/g,'')"
          />
        </el-form-item>
        <el-form-item label="银行" prop="bank">
          <el-select
            v-model="card.bank"
            filterable
            placeholder="请选择所属银行"
          >
            <el-option
              v-for="item in options"
              :key="item.dictName"
              :label="item.dictName"
              :value="item.dictId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="注册手机号" prop="phone">
          <el-input
            v-if="phoneShow"
            :model-value="hidden(card.phone, 3, 4)"
            oninput="value=value.replace(/[^\d]/g,'')"
            maxlength="11"
            style="width: 120px"
            @focus="focusPhoneInput"
          />
          <el-input
            v-else
            v-model="card.phone"
            placeholder="请输入手机号"
            oninput="value=value.replace(/[^\d]/g,'')"
            maxlength="11"
            style="width: 300px"
          >
            <template #append>
              <el-button
                type="primary"
                :loading="codeloading"
                @click="sendCode(card.phone)"
              >
                <span v-if="!codeloading">获取验证码</span>
                <span v-else>{{ count }} s</span>
              </el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="验证码" prop="code">
          <el-input
            v-model="card.code"
            oninput="value=value.replace(/[^\d]/g,'')"
            placeholder="请输入验证码"
            maxlength="6"
            style="width: 120px"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" :loading="submitLoading" @click="confirm(formRef)">{{ dialogData.confirm || '确定' }}</el-button>
          <el-button @click="dialogData.isVisible = false, phoneShow = true">取消</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onBeforeMount } from 'vue'
import {
  accountGetById,
  getSelect,
  bankDelete,
  bankUpdate,
  bankAdd,
  getCode,
} from '@/api/account'
import defaultBank from '@/assets/images/bank/bankCard.png'

const TIME_COUNT = 60 // 更改倒计时时间
const formRef = ref(null)
const submitLoading = ref(false)
const err = ref('账&#12288;号：')
const bankArr = ref('')
const show = ref(true)
const codeloading = ref(false)
const dialogData = ref({})
const count = ref('')
const mobile = ref('13444444444')
const options = ref([])
const formList = ref({
  1: 'form',
  2: 'unbind',
  3: 'card'
})
// 绑定银行卡
const form = ref({
  cardName: '',
  cardNumber: '',
  bank: '',
  phone: '',
  code: ''
})
// 解绑
const unbinds = ref({
  phone: '',
  code: ''
})
// 更换
const card = ref({
  cardName: '',
  cardNumber: '',
  bank: '',
  phone: '',
  code: ''
})
const rules = ref({
  cardName: [{ required: true, message: '请输入持卡人姓名', trigger: 'blur' }],
  cardNumber: [
    { required: true, message: '请输入银行卡号', trigger: 'blur' },
    { required: true, pattern: /^([1-9]{1})(\d{15}|\d{18})$/, message: '请输入正确的银行卡号', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { required: true, pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  code: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
  bank: [{ required: true, message: '请输入选择银行', trigger: 'blur' }],
  oldCardNumber: [{ required: true, message: '请输入原银行卡号', trigger: 'blur' }]
})
const privacyTime = ref(0)
const cardNumberShow = ref(true)// 是否显示卡号脱敏
const phoneShow = ref(true) // 是否显示手机号脱敏
const oldCardNumber = ref('')
const oldPhone = ref('')
const timer = ref(null)

onBeforeMount(() => {
  bankDetails()
  bankName()
  privacyTime.value = localStorage.getItem('privacyTime')
})
const closeDialog = () => {
  card.value.cardNumber = card.value.cardNumber
    ? card.value.cardNumber
    : oldCardNumber.value
  card.value.phone = card.value.phone ? card.value.phone : oldPhone.value
  formRef.value.resetFields()
}
const focusPhoneInput = () => {
  phoneShow.value = false
  card.value.phone = ''
}
const focusCardNunberInput = () => {
  cardNumberShow.value = false
  card.value.cardNumber = ''
}
// 获取验证码
const sendCode = async (phone) => {
  await formRef.value.validateField('phone', async (valid) => {
    if (valid) {
      if (!timer.value) {
        const res = await getCode({ phone })
        if (res.code === '') {
          ElMessage({
            message: '发送成功，请注意查看手机短信',
            type: 'success',
          })
        }
        codeloading.value = true
        count.value = TIME_COUNT
        timer.value = setInterval(() => {
          if (count.value > 0 && count.value <= TIME_COUNT) {
            count.value--
          } else {
            show.value = true
            clearInterval(timer.value) // 清除定时器
            timer.value = null
            codeloading.value = false
          }
        }, 1000)
      }
    } else {
      return false
    }
  })
}
const btKeyUp = (e) => {
  e.target.value = e.target.value.replace(
    /[`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘’，。、' ']/g,
    ''
  )
}
// 解绑
const unbind = async (v) => {
  try {
    submitLoading.value = true
    const res = await bankDelete(unbinds.value)
    if (res.code === '') {
      ElMessage({
        message: '解绑成功',
        type: 'success',
      })
      bankDetails()
      dialogData.value.isVisible = false
    }
  } finally {
    submitLoading.value = false
  }
}
// 更换银行卡
const replaceCard = (v) => {
  dialogData.value = {
    title: '更换银行卡',
    isVisible: true,
    confirm: '更换',
    type: v,
  }
  card.value = bankArr.value
  cardNumberShow.value = true
  oldCardNumber.value = card.value.cardNumber
  oldPhone.value = card.value.phone
}
// 绑定银行卡
const bindCard = (v) => {
  dialogData.value = {
    title: '绑定银行卡',
    isVisible: true,
    confirm: '绑定',
    type: v,
  }
  card.value = {
    cardName: '',
    cardNumber: '',
    bank: '',
    phone: '',
    code: '',
  }
}
// 解绑银行卡
const delBank = (v) => {
  dialogData.value = {
    title: '解绑银行卡',
    isVisible: true,
    confirm: '解绑',
    type: v,
  }
}
// 确认
const confirm = async (formEl) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (formList.value[dialogData.value.type] === 'card') {
        changeBank()
      } else if (formList.value[dialogData.value.type] === 'form') {
        addBank()
      } else if (formList.value[dialogData.value.type] === 'unbind') {
        unbind()
      }
    } else {
      return false
    }
  })
}
// 更换账户
const changeBank = async () => {
  try {
    submitLoading.value = true
    const res = await bankUpdate(card.value)
    if (res.code === '') {
      ElMessage({
        message: '更换成功',
        type: 'success',
      })
      bankDetails()
      dialogData.value.isVisible = false
    }
  } finally {
    submitLoading.value = false
  }
}
// 绑定账户
const addBank = async () => {
  try {
    submitLoading.value = true
    const res = await bankAdd(form.value)
    if (res.code === '') {
      ElMessage({
        message: '绑定成功',
        type: 'success',
      })
      bankDetails()
      dialogData.value.isVisible = false
    }
  } finally {
    submitLoading.value = false
  }
}
// 查询账户
const bankDetails = async () => {
  const res = await accountGetById({})
  if (res.code === '') {
    if (JSON.stringify(res.data) === '{}') {
      show.value = false
    } else {
      bankArr.value = res.data
      show.value = true
    }
  }
}
const bankName = async () => {
  const res = await getSelect({ dictName: '所属银行' })
  options.value = res.data
}
// 中间部分
const hidden = (str, frontLen, endLen) => {
  if (str && frontLen && endLen) {
    let endLenData = 0
    if (str.length !== 2) {
      endLenData = endLen
    }
    const len = str.length - frontLen - endLenData
    let xing = ''
    for (let i = 0; i < len; i++) {
      xing += '*'
    }
    return (
      str.substring(0, frontLen) +
      xing +
      str.substring(str.length - endLenData)
    )
  }
}
</script>

<style lang="scss" scoped>
.accont_Page {
  :deep(.el-card__header ){
    font-size: 24px;
    font-weight: bold;
  }
}
.text_item {
  padding: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  .leftImg {
    width: 260px;
    height: 68px;
    overflow: hidden;
    img {
      width: 260px;
      height: 68px;
    }
  }
  .noAccount {
    flex: 1;
    font-size: 18px;
    margin-left: 30px;
  }
  .bankName {
    font-size: 18px;
    color: #333333;
    .bankNumber {
      display: flex;
      justify-content: flex-start;
      align-items: center;
      line-height: 30px;
      .bankNumber_1 {
        font-size: 18px;
      }
      .bankNumber_2 {
        font-size: 22px;
      }
    }
    .bankPeople {
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
  .btnList {
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 15px;
    cursor: pointer;
    .cutBank {
      background: rgba(58, 104, 242, 0.2);
      border: 1px solid #3a68f2;
      opacity: 0.5;
      border-radius: 4px;
      font-size: 16px;
      color: #3a68f2;
      width: 100px;
      height: 38px;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 30px;
    }
    .changeBank {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 100px;
      height: 38px;
      background: #3a68f2;
      border-radius: 4px;
      color: #ffffff;
    }
  }
}
.dialog-footer {
  text-align: center;
  .el-button {
    padding: 15px 30px;
  }
}
.unbind {
  height: 40px;
  line-height: 40px;
  span {
    display: inline-block;
    font-size: 14px;
    color: #606266;
    &:nth-child(1) {
      width: 120px;
      text-align: right;
      padding-right: 12px;
      font-weight: 600;
    }
    &:nth-child(2) {
      margin-right: 50px;
    }
  }
  .el-button {
    padding: 6px 20px;
  }
}
.card {
  font-size: 18px;
  color: #84878d;
  // font-weight: 600;
}
.el-form {
  .el-form-item {
    label {
      font-weight: 400 !important;
    }
  }
}
.sendCode {
  margin-left: 20px;
}
</style>
